import axios from "axios";

/**
 * 封装 http 请求
 * @param url
 * @param methods
 * @param params
 * @param contentType
 * @returns {Promise<unknown>}
 */
function request(url, methods, params, contentType="application/x-www-form-urlencoded") {
    return new Promise((resolve, reject) => {
        let param = {};
        if (contentType === 'application/x-www-form-urlencoded'){
            let paramsArr = [];
            for(let key in params){
                paramsArr.push(`${key}=${params[key]}`)
            }
            param = paramsArr.join('&');
        } else {
            param = params;
        }
        axios({
            url: url,
            method: methods,
            data: param,
            headers: {
                'Content-Type': contentType
            }
        }).then(response => {
            if (response.status === 200){
                resolve(response.data);
            } else {
                reject(response);
            }
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export default request;